package o2o.web.actions.order.company;

import com.jinyou.utils.common.*;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import jPush.dao.JPushMessage;
import notice.dao.NoticeType;
import o2o.cache.company.postman.CompanyTypeRelationMemory;
import o2o.cache.company.postman.PostCompanyMemory;
import o2o.cache.company.postman.PostTypeMemory;
import o2o.cache.company.postman.PostmanSignCompanyMemory;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.order.OrderPayMemory;
import o2o.cache.order.OrderStatusMemory;
import o2o.cache.order.admin.CityOrderMemoryMan;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.postman.PostmanPositionMemory;
import o2o.cache.sys.SysConfigDepositMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.cache.wallet.UserWalletMemory;
import o2o.config.dao.UserDaoSql;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.company.postman.PostCompanyInfo;
import o2o.dao.PO.company.postman.PostmanSignCompanyInfo;
import o2o.dao.PO.company.postman.SIGN_COMPANY_STATUS;
import o2o.dao.PO.order.*;
import o2o.postman.model.CityPostman;
import o2o.dao.PO.postman.PostmanPositionInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.wallet.UserWallet;
import o2o.dao.VO.order.OrderGoodsLabelVO;
import o2o.dao.VO.order.OrderInfoVO;
import o2o.dao.VO.order.OrderPostmanTroubleVO;
import o2o.dao.VO.postman.CityPostmanVO;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.web.actions.notice.Notice;
import o2o.web.actions.order.OrderListMan;
import o2o.web.actions.order.OrderMan;
import o2o.web.actions.postman.PostmanMan;
import o2o.web.actions.sys.GrabOrderModeMan;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @User: @Created by yangtk
 * @Date: @Date 2019/8/13 9:35
 * @Classname: PostCompanyOrderController
 * @To change this template use File | Settings | File Templates.
 */
@Controller
public class PostCompanyOrderController {

    // 未分配配送员的
    @RequestMapping("company/order/undelivery/list")
    @ResponseBody
    public String company_order_new_list(String token, Long companyId, Integer type, Long createTime, Integer size, Integer isLoadMore) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        PostCompanyInfo postCompanyInfo = null;
        if (companyId == null) {
            postCompanyInfo = PostCompanyMemory.getInstance().getByUsername(user.getUsername());
        } else {
            postCompanyInfo = PostCompanyMemory.getInstance().getById(companyId);
        }
        if (postCompanyInfo == null) {
            return AjaxResult.errorResult("未获取到公司信息");
        }
        if (createTime == null) {
            createTime = 0L;
        }
        if (size == null) {
            size = 20;
        }
        if (isLoadMore == null || isLoadMore != 1) {
            isLoadMore = 0;
        }
        // 获取公司当前的类型信息
        Set<Long> set = CompanyTypeRelationMemory.getInstance().listOfByCompanyId(postCompanyInfo.getId());
        if (set == null) {
            return AjaxResult.successResult(0, null);
        }
        Set<Integer> typeSet = set.stream().map(id -> PostTypeMemory.getInstance().getById(id)).filter(postTypeInfo -> postTypeInfo != null && postTypeInfo.getType() != null).map(a -> a.getType())
                .filter(t -> type == null ? true : t == type).collect(Collectors.toSet());
        if (typeSet == null || typeSet.isEmpty()) {
            return AjaxResult.successResult(0, null);
        }
        Set<Long> companyIdSet = new HashSet<>();
        companyIdSet.add(postCompanyInfo.getId());
        List<OrderInfo> orderInfoList = CityOrderMemoryMan.cityUnDeliveryByCompanyIdList(postCompanyInfo.getCity(), createTime, size, isLoadMore, typeSet, typeSet, companyIdSet, null);

        if (ValidateUtil.isAbsList(orderInfoList)) {
            List<OrderInfoVO> orderInfoVOList = new ArrayList<OrderInfoVO>();
            for (int i = 0; i < orderInfoList.size(); i++) {
                if (null == orderInfoList.get(i)) {
                    continue;
                }
                OrderInfoVO orderInfoVO = new OrderInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(orderInfoList.get(i), orderInfoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == orderInfoVO) {
                    continue;
                }
                if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                }
                if (null != orderInfoVO.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfoVO.getOrderType()) {
                    List<OrderGoodsLabelVO> labels = OrderListMan.listOfOrderNO(orderInfoVO.getOrderNo());
                    orderInfoVO.setLabelList(labels);
                }
                orderInfoVOList.add(orderInfoVO);
            }
            return AjaxResult.successResult(orderInfoVOList.size(), orderInfoVOList);
        }
        return AjaxResult.successResult(0, null);
    }

    //获取进行中的订单  公司
    @RequestMapping(method = RequestMethod.POST, value = "/company/order/ing/list")
    @ResponseBody
    public String order_admin_ing_list(String token, Integer type, Long companyId,
                                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                                       @RequestParam(value = "size", defaultValue = "20") Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }
        PostCompanyInfo companyInfo = null;
        if (companyId == null) {
            companyInfo = PostCompanyMemory.getInstance().getByUsername(user.getUsername());
        } else {
            companyInfo = PostCompanyMemory.getInstance().getById(companyId);
        }
        if (companyInfo == null) {
            return AjaxResult.errorResult("获取不到公司信息");
        }
        Set<Long> set = CompanyTypeRelationMemory.getInstance().listOfByCompanyId(companyInfo.getId());
        if (set == null) {
            return AjaxResult.successResult(0, 0, null);
        }
        Set<Integer> typeSet = set.stream().map(id -> PostTypeMemory.getInstance().getById(id)).filter(postTypeInfo -> postTypeInfo != null && postTypeInfo.getType() != null).map(a -> a.getType())
                .filter(t -> type == null ? true : t == type).collect(Collectors.toSet());
        if (typeSet == null) {
            return AjaxResult.successResult(0, 0, null);
        }
        String orderTypeStr = " and  orderType In (" + StringUtils.join(typeSet, ",") + ")";
        //v2
        List<OrderInfo> list = null;

        // 获取城市代理下所有店铺
        StringBuffer sb = new StringBuffer();
        sb.append(" from ").append(PojoTables.OrderInfo).append(" where delFlag = 0 ").append(orderTypeStr).append(" and  (orderStatus!=").append(ORDER_STATUS.OVER).append(" and orderStatus!=").append(ORDER_STATUS.CANCEL)
                .append(" and orderStatus!=").append(ORDER_STATUS.CANCEL_BY_SYSTEM).append(" and orderStatus!=").append(ORDER_STATUS.PAYED_CANCEL)
                .append(" and orderStatus!=").append(ORDER_STATUS.SHOP_REFUSED)
                .append(" ) ").append(" and grabCompanyId=").append(companyInfo.getId())
                .append(" and (LEFT(orderNo,1) = 'M' or LEFT(orderNo,1) = 'P' or LEFT(orderNo,1) = '1'or LEFT(orderNo,1) = '2' or LEFT(orderNo,1) = '3' or LEFT(orderNo,1) = '4'  or LEFT(orderNo,1) = '5') ")
                .append(" ORDER BY isUrgent desc,createTime DESC ");

        Long totalCount = 0l;
        try {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("select * ").append(sb.toString()).append(" LIMIT ").append((page - 1) * size).append(",").append(size);
            list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbSql.toString());

            StringBuffer sbCount = new StringBuffer();
            sbCount.append("select count(1) counts ").append(sb.toString());
            totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }
        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = OrderListMan.convertToVo(list, false);
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(totalCount, voList.size(), voList);
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }

    //获取全部订单  公司
    @RequestMapping(method = RequestMethod.POST, value = "/company/order/all/list")
    @ResponseBody
    public String order_admin_all_list(String token, Long companyId,
//                                       Integer type,
                                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                                       @RequestParam(value = "size", defaultValue = "20") Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        PostCompanyInfo postCompanyInfo = null;
        if (companyId == null) {
            postCompanyInfo = PostCompanyMemory.getInstance().getByUsername(user.getUsername());
        } else {
            postCompanyInfo = PostCompanyMemory.getInstance().getById(companyId);
        }
        if (postCompanyInfo == null) {
            return AjaxResult.errorResult("未获取到配送公司信息");
        }

        StringBuilder sql = new StringBuilder();
        sql.append(" from ").append(PojoTables.OrderInfo)
                .append(" where delFlag = 0")
                .append(" and (grabCompanyId = ").append(postCompanyInfo.getId())
                .append(" or (").append("grabCompanyId is null and find_in_set(").append(postCompanyInfo.getId()).append(",").append("canGrabCompanyIds").append(")))");

        StringBuilder selectSql = new StringBuilder();
        selectSql.append("select * ").append(sql.toString()).append(" order by createTime desc limit ").append((page - 1) * size).append(",")
                .append(size);
        StringBuilder countSql = new StringBuilder();
        countSql.append("select count(*) as counts ").append(sql.toString());
        List<OrderInfo> list = null;
        long totalCount = 0L;
        try {
            list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, selectSql.toString());
            totalCount = UserDaoSql.getInstance().getCount(countSql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = OrderListMan.convertToVo(list, false);
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(totalCount, voList.size(), voList);
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }

    //获取已完成的订单  公司
    @RequestMapping(method = RequestMethod.POST, value = "/company/order/finish/list")
    @ResponseBody
    public String order_admin_finish_list(String token, Long companyId,
                                          @RequestParam(value = "page", defaultValue = "1") Integer page,
                                          @RequestParam(value = "size", defaultValue = "20") Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        PostCompanyInfo postCompanyInfo = null;
        if (companyId == null) {
            postCompanyInfo = PostCompanyMemory.getInstance().getByUsername(user.getUsername());
        } else {
            postCompanyInfo = PostCompanyMemory.getInstance().getById(companyId);
        }
        if (postCompanyInfo == null) {
            return AjaxResult.errorResult("未获取到配送公司信息");
        }
        List<OrderInfo> list = null;
        StringBuffer sb = new StringBuffer();
        sb.append(" from ").append(PojoTables.OrderInfo).append(" where delFlag = 0 ").append(" and grabCompanyId=").append(postCompanyInfo.getId()).append(" and (LEFT(orderNo,1) = 'M' or LEFT(orderNo,1) = 'P' or LEFT(orderNo,1) = '1'or LEFT(orderNo,1) = '2' or LEFT(orderNo,1) = '3' or LEFT(orderNo,1) = '4'  or LEFT(orderNo,1) = '5') and orderStatus='").append(ORDER_STATUS.OVER)
                .append("' ORDER BY createTime DESC ");

        Long totalCount = 0l;
        try {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("select * ").append(sb.toString()).append(" LIMIT ").append((page - 1) * size).append(",").append(size);
            list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbSql.toString());
            StringBuffer sbCount = new StringBuffer();
            sbCount.append("select count(1) counts ").append(sb.toString());
            totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }
        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = OrderListMan.convertToVo(list, false);
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(totalCount, voList.size(), voList);
            }
        }

        return AjaxResult.successResult(0, 0, null);
    }

    //订单查询 公司
    @RequestMapping(method = RequestMethod.POST, value = "/company/order/search/list")
    @ResponseBody
    public String order_admin_list(String token, Integer orderType,
                                   Long companyId,
                                   String shopUsername, String shopName,
                                   String name, String phone, String address, //购买人信息
                                   String orderNo, //订单编号
                                   Integer orderStatus,//订单状态
                                   String postmanUsername,//配送员账号
                                   Long shopId,//店铺ID
                                   Long startTime, Long endTime,
                                   @RequestParam(value = "page", defaultValue = "1") Integer page,
                                   @RequestParam(value = "size", defaultValue = "20") Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        PostCompanyInfo companyInfo = null;
        if (companyId == null) {
            companyInfo = PostCompanyMemory.getInstance().getByUsername(user.getUsername());
        } else {
            companyInfo = PostCompanyMemory.getInstance().getById(companyId);
        }
        if (companyInfo == null) {
            return AjaxResult.errorResult("未获取到公司信息");
        }

        List<OrderInfo> list = new ArrayList<>();
        //不按店铺查
        StringBuffer sb = new StringBuffer();
        //数据库中查出订单编号  再去缓存取内容
        if (ValidateUtil.isNotNull(shopUsername) || ValidateUtil.isNotNull(shopName)) {

            sb.append(" from ").append(PojoTables.OrderInfo).append(" a left join ").append(PojoTables.ShopInfo)
                    .append(" b on a.shopId = b.id where b.id is not null and b.delFlag = 0 and a.delFlag = 0 ").append("and (a.grabCompanyId=").append(companyInfo.getId())
                    .append(" or (").append("a.grabCompanyId is null and find_in_set(").append(companyInfo.getId()).append(",").append("a.canGrabCompanyIds").append(")))");
            if (ValidateUtil.isNotNull(shopUsername)) {
                sb.append(" and b.shopName like '%").append(shopUsername).append("%' ");
            }
            if (ValidateUtil.isNotNull(shopName)) {
                sb.append(" and b.shopName like '%").append(shopName).append("%' ");
            }
            if (ValidateUtil.isNotNull(postmanUsername)) {
                sb.append(" and a.postManUsername like '%").append(postmanUsername).append("%' ");
            }
            if (ValidateUtil.isNotNull(name)) {
                sb.append(" and a.buyer like '%").append(name).append("%' ");
            }
            if (ValidateUtil.isNotNull(phone)) {
                sb.append(" and (a.telephone like '%").append(phone).append("%' or ")
                        .append(" a.username like '%").append(phone).append("%')");
            }
            if (ValidateUtil.isNotNull(address)) {
                sb.append(" and ( a.address like '%").append(address).append("%' ");
                sb.append(" or a.address2 like '%").append(address).append("%' )");
            }
            if (ValidateUtil.isNotNull(orderNo)) {
                sb.append(" and a.orderNo like '%").append(orderNo).append("%' ");
            }
            if (null != orderStatus && orderStatus > 0) {
                sb.append(" and a.orderStatus = ").append(orderStatus);
            }

            if (null != orderType && orderType > 0) {
                sb.append(" and a.orderType = ").append(orderType);
            }

            if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
                sb.append(" and a.createTime Between ").append(startTime).append(" and ").append(endTime);
            }
        } else {
            sb.append(" from ").append(PojoTables.OrderInfo).append(" a where delFlag = 0 ").append("and ( a.grabCompanyId=").append(companyInfo.getId())
                    .append(" or (").append("a.grabCompanyId is null and find_in_set(").append(companyInfo.getId()).append(",").append("a.canGrabCompanyIds").append(")))");
            if (ValidateUtil.isNotNull(name)) {
                sb.append(" and buyer like '%").append(name).append("%' ");
            }
            if (ValidateUtil.isNotNull(postmanUsername)) {
                sb.append(" and a.postManUsername like '%").append(postmanUsername).append("%' ");
            }
            if (ValidateUtil.isNotNull(phone)) {
                sb.append(" and (a.telephone like '%").append(phone).append("%' or ")
                        .append(" a.username like '%").append(phone).append("%')");
            }
            if (ValidateUtil.isNotNull(address)) {
                sb.append(" and ( address like '%").append(address).append("%' ");
                sb.append(" or address2 like '%").append(address).append("%' ) ");
            }
            if (ValidateUtil.isNotNull(orderNo)) {
                sb.append(" and orderNo like '%").append(orderNo).append("%' ");
            }
            if (null != orderStatus && orderStatus > 0) {
                sb.append(" and orderStatus = ").append(orderStatus);
            }
            if (null != orderType && orderType > 0) {
                sb.append(" and orderType = ").append(orderType);
            }

            if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
                sb.append(" and createTime Between ").append(startTime).append(" and ").append(endTime);
            }
            if (ValidateUtil.isAbsLong(shopId)) {
                sb.append(" and shopId= '").append(shopId).append("'");
            }
        }
        Long totalCount = 0l;
        try {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("select count(a.orderNo) as counts ");
            sbSql.append(sb.toString());
            totalCount = UserDaoSql.getInstance().getCount(sbSql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            totalCount = 0l;
        }
        List<HashMap<String, Object>> listMap = null;
        try {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("select  a.orderNo , a.createTime ");
            sb.append(" ORDER BY createTime DESC ");
            sbSql.append(sb.toString());
            sbSql.append(" limit ").append((page - 1) * size).append(",").append(size);
            listMap = UserDaoSql.getInstance().queryBySql(sbSql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            listMap = null;
        }
        if (ValidateUtil.isAbsList(listMap)) {
            for (int i = 0; i < listMap.size(); i++) {
                if (null == listMap.get(i)) {
                    continue;
                }
                String no = (String) listMap.get(i).get("orderNo");
                if (ValidateUtil.isNull(no)) {
                    continue;
                }
                OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(no);
                if (null == orderInfo) {
                    continue;
                }
                list.add(orderInfo);
            }
        }

        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = new ArrayList<OrderInfoVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                OrderInfoVO orderInfoVO = new OrderInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == orderInfoVO) {
                    continue;
                }
                if (ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                }
                voList.add(orderInfoVO);
            }
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(totalCount, voList.size(), voList);
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }


    //指定配送员 公司
    @RequestMapping(method = RequestMethod.POST, value = "/company/order/postman/add")
    @ResponseBody
    public String order_postman_add(String token, Long companyId, String sysAppKey, String orderNo, String username) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        PostCompanyInfo companyInfo = null;
        if (companyId == null) {
            companyInfo = PostCompanyMemory.getInstance().getByUsername(user.getUsername());
        } else {
            companyInfo = PostCompanyMemory.getInstance().getById(companyId);
        }
        if (companyInfo == null) {
            return AjaxResult.errorResult("未获取到公司信息");
        }
        //判断当前订单状体
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("当前订单不存在，请查证");
        }
        if (GrabOrderModeMan.getGrabOrderMode(orderInfo.getAgentId()) == GRAB_ORDER_MODE.ONLY_GRAB_MODE) {
            return AjaxResult.errorResult("当前仅抢单模式，无法调度");
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择配送员");
        }
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("请选择订单");
        }

        CityPostman postman = CityPostmanMemory.getInstance().getPostman(username);
        if (null == postman) {
            return AjaxResult.errorResult("当前账号无效");
        }
        if (ValidateUtil.isNotAbsInteger(postman.getIsWork())) {
            return AjaxResult.errorResult("您选择的账号未上班，请选择其他账号");
        }
        if (0 == postman.getIsWork()) {
            return AjaxResult.errorResult("您选择的账号未上班，请选择其他账号.");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY
                && (null == postman.getIsVerify() || 0 != 1 - postman.getIsVerify())) {
            return AjaxResult.errorResult("该账号未通过认证，无法派单");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE) {
            UserInfo postmanUser = UserInfoMemory.getInstance().getUserInfo(username);
            if (null != postmanUser && null != postmanUser.getIsCert() && 0 == 1 - postmanUser.getIsCert()) {
                //已认证
            } else {
                return AjaxResult.errorResult("该账号未通过实名认证，无法派单");
            }
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(username);
            if (null == userWallet) {
                return AjaxResult.errorResult("该账号未缴纳押金，无法派单");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("该账号未缴纳押金，无法派单！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
            if (null == money) {
                money = 0d;
            }

            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("该账号员缴纳的押金不足，请先缴纳押金");
            }
        }

//        //判断当前订单状体
//        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
//        if (null == orderInfo) {
//            return AjaxResult.errorResult("当前订单不存在，请查证");
//        }
        // i
        if (orderInfo.getOrderType() != postman.getType()) {
            return AjaxResult.errorResult("当前配送员不支持该类型的订单");
        }

        if (ORDER_STATUS.OVER == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.PAYED_CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_REFUSED == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus()
                || (ORDER_STATUS.POSTMAN_ZHIDING == orderInfo.getOrderStatus() && (SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY == null || SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY == 0))
                || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()
                || (null != orderInfo.getOrderType() && 0 != ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType() && ORDER_STATUS.SUBMIT == orderInfo.getOrderStatus())) {
            return AjaxResult.errorResult("当前订单状态不允许操作");
        }

        // 如果已有配送员，先清除上次指定人员
        String lastPostman = orderInfo.getPostManUsername();
        if (username.equalsIgnoreCase(lastPostman)) {
            return AjaxResult.errorResult("骑手配送中，无需重复指定");
        }
        if (null != SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY && 0 == SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY) {
            // 只能指定一次
            if (ValidateUtil.isNotNull(lastPostman)) {
                return AjaxResult.errorResult("骑手配送中，不能重复指派");
            }
        }

        //获取配送员信息
        UserInfo postmanInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == postmanInfo) {
            return AjaxResult.errorResult("当前配送员不存在，请查证后制定");
        }

        //当前配送员是否工作状态

        //todo 配送员送货个数 ，是否继续可以派单
        int orderSts = ORDER_STATUS.POSTMAN_ZHIDING;

        boolean isNeedAccept = true; // 骑手是否需要接单
        if (!OrderMan.systemOperatePostmanNeedAccept()) {
            isNeedAccept = false;
        }
        if (!isNeedAccept) {
            orderSts = ORDER_STATUS.POSTMAN_SURE;
        }
        Long time = DateUtils.getCurrTime();
        //保存到订单上
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(orderSts)
                .append(",updateUser = '").append(user.getUsername()).append("',postmanUsername='")
                .append(postmanInfo.getUsername()).append("',postmanName='").append(postmanInfo.getName()).append("',postmanPhone='")
                .append(postmanInfo.getTelPhone())
                .append("',postmanImageUrl='").append(postmanInfo.getSignPhoto()).append("' ");
        if (!isNeedAccept) {
            sb.append(" ,postmanSureTime=").append(time);
        }
        sb.append(",grabCompanyId=").append(companyInfo.getId());
        sb.append("  where delFlag = 0 and  orderNo ='").append(orderNo).append("'");
        OrderStatus orderStatus = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_ZHIDING, user.getUsername(), time);
        Connection conn = null;
        try {
            conn = UserDaoSql.getInstance().getConnection(true);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("数据库");
        }

        boolean isUpdateOrderPayInfo = false;
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString(), conn);
            UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, orderStatus, conn);
            if (!isNeedAccept) {
                OrderStatus orderStatus2 = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_SURE, user.getUsername(), time);
                UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, orderStatus2, conn);
            }
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(conn);
            return AjaxResult.errorResult("指定的失败，请稍后");
        } finally {
            UserDaoSql.getInstance().close(conn);
        }

        // 清除上次的骑手
        if (ValidateUtil.isNotNull(lastPostman)) {
            OrderInfoMemory.getInstance().removePostmanOrderInfo(lastPostman, orderNo);
        }
        //插入订单状态缓存
        OrderStatusMemory.getInstance().addStatus(orderNo);
        //修改订单缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);

        if (isUpdateOrderPayInfo) {
            OrderPayMemory.getInstance().modify(orderNo);
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderNo);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        }
        if (isNeedAccept) {
            Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），系统已指定配送员，请耐心等待");
        } else {
            Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），配送员已接单");
        }
        return AjaxResult.successResult();
    }


    //获取配送员列表及对应的位置 公司
    @RequestMapping(method = RequestMethod.POST, value = "/company/postman/position/list")
    @ResponseBody
    public String city_postman_list(String token,
                                    Long companyId,
                                    Integer type,
                                    String username, String name,
                                    Double lat, Double lng,
                                    @RequestParam(value = "page", defaultValue = "1") Integer page,
                                    @RequestParam(value = "size", defaultValue = "20") Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        PostCompanyInfo postCompanyInfo = null;
        if (companyId == null) {
            postCompanyInfo = PostCompanyMemory.getInstance().getByUsername(user.getUsername());
        } else {
            postCompanyInfo = PostCompanyMemory.getInstance().getById(companyId);
        }
        if (postCompanyInfo == null) {
            return AjaxResult.errorResult("未获取到配送公司信息");
        }
        List<PostmanSignCompanyInfo> signCompanyInfos = PostmanSignCompanyMemory.getInstance().listOfCompanyId(postCompanyInfo.getId(), username, type, SIGN_COMPANY_STATUS.pass);
        List<CityPostman> list = signCompanyInfos == null ? null : signCompanyInfos.stream().filter(u -> u.getUsername() != null && StringUtils.isNotEmpty(u.getUsername()))
                .map(u -> CityPostmanMemory.getInstance().getPostman(u.getUsername())).collect(Collectors.toList());
        list = list != null ? list.stream().filter(u -> u != null && (type == null ? true : u.getType() == type)).collect(Collectors.toList()) : null;
        if (ValidateUtil.isAbsList(list)) {
            List<CityPostmanVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                CityPostman cityPostman = list.get(i);
                if (null == cityPostman) {
                    continue;
                }
                //认证
                if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY
                        && (null == cityPostman.getIsVerify() || 0 != 1 - cityPostman.getIsVerify())) {
                    continue;
                }
                if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE) {
                    UserInfo postmanUser = UserInfoMemory.getInstance().getUserInfo(cityPostman.getUsername());
                    if (null != postmanUser && null != postmanUser.getIsCert() && 0 == 1 - postmanUser.getIsCert()) {
                        //已认证
                    } else {
                        continue;
                    }
                }

                //押金
                if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
                    // 必须缴纳
                    //验证押金金额是否满足
                    UserWallet userWallet = UserWalletMemory.getInstance().getWallet(cityPostman.getUsername());
                    if (null == userWallet) {
                        continue;
                    }
                    if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                        continue;
                    }
                    //必须缴纳的押金金额
                    Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
                    if (null == money) {
                        money = 0d;
                    }

                    if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                        continue;
                    }
                }
                CityPostmanVO vo = PostmanMan.getOne(cityPostman);
                if (null == vo) {
                    continue;
                }
                if (ValidateUtil.isNotNull(username) && !vo.getUsername().equals(username)) {
                    continue;
                }
                if (ValidateUtil.isNotNull(name) && !vo.getName().equals(name)) {
                    continue;
                }
                //获取配送员位置信息
                PostmanPositionInfo info = PostmanPositionMemory.getInstance().get(vo.getId());
                if (null != info) {
                    Integer count = OrderInfoMemory.getInstance().countOfDeliveryIng(vo.getUsername());
                    if (ValidateUtil.isAbsInteger(count)) {
                        info.setOrderCount(count);
                    }
                    //距离
                    if (ValidateUtil.isLatLng(lat, lng)
                            && ValidateUtil.isLatLng(info.getLat(), info.getLng())) {
                        Double distinct = Geohash.distance(lat, lng, info.getLat(), info.getLng());
                        if (ValidateUtil.isNotAbsDouble(distinct)) {
                            vo.setDistinct(distinct);
                        }
                    }
                }
                vo.setPositionInfo(info);//配送员所在的位置
                voList.add(vo);
            }
            if (ValidateUtil.isAbsList(voList)) {
                Collections.sort(voList, new Comparator<CityPostmanVO>() {
                    // 先按距离升序，序号相同 则空闲升序
                    public int compare(CityPostmanVO arg0, CityPostmanVO arg1) {
                        if (arg1.getDistinct().compareTo(arg0.getDistinct()) == 0) {
                            return arg1.getDistinct().compareTo(arg0.getDistinct()) > 0 ? 1 : -1;
                        } else {
                            return (int) (arg0.getPositionInfo().getOrderCount() - arg1.getPositionInfo().getOrderCount());
                        }
                    }
                });
            }
            JYPageUtils.PageList pageList = JYPageUtils.getList(voList, page, size);
            if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
                return AjaxResult.successResult(pageList.totalCount, pageList.list.size(), pageList.list);
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }


    //配送异常订单列表 公司异常订单
    @RequestMapping(method = RequestMethod.POST, value = "/company/order/postman/trouble/list")
    @ResponseBody
    public String order_trouble_list(String token, Long companyId,
                                     String orderNo,
                                     String postmanUsername,
                                     Long startTime, Long endTime,
                                     @RequestParam(value = "page", defaultValue = "1") Integer page,
                                     @RequestParam(value = "size", defaultValue = "20") Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        PostCompanyInfo postCompanyInfo = null;
        if (companyId == null) {
            postCompanyInfo = PostCompanyMemory.getInstance().getByUsername(user.getUsername());
        } else {
            postCompanyInfo = PostCompanyMemory.getInstance().getById(companyId);
        }
        if (postCompanyInfo == null) {
            return AjaxResult.errorResult("未获取到配送公司信息");
        }

        StringBuilder sql = new StringBuilder();
        sql.append(" from ").append(PojoTables.ORDER_POSTMAN_TROUBLE)
                .append(" as a ").append("left join ").append(PojoTables.OrderInfo)
                .append(" as o ").append(" on a.orderNo = o.orderNo and a.delFlag =0 and o.delFlag = 0 ")
                .append(" where o.grabCompanyId = ").append(postCompanyInfo.getId());
        if (ValidateUtil.isNotNull(orderNo)) {
            sql.append(" and o.orderNo like '%").append(orderNo).append("%'");
        }
        if (ValidateUtil.isAbsLong(startTime) && startTime > 0) {
            sql.append(" and a.createTime >").append(startTime);
        }
        if (StringUtils.isNotEmpty(postmanUsername)) {
            sql.append(" and a.username like '%").append(postmanUsername).append("%'");
        }
        if (ValidateUtil.isAbsLong(endTime) && endTime > 0) {
            sql.append(" and a.createTime <").append(endTime);
        }
//        sql.append(" order by createTime,orderNo desc limit ").append((page - 1) * size).append(",").append(size);
        List<OrderPostmanTrouble> list = null;
        long count = 0;
        StringBuilder selectSql = new StringBuilder();
        selectSql.append("select a.* ").append(sql.toString()).append(" order by createTime,orderNo desc limit ").append((page - 1) * size).append(",").append(size);
        StringBuilder countSql = new StringBuilder();
        countSql.append("select count(a.id) as counts ").append(sql.toString());
        try {
            list = (List<OrderPostmanTrouble>) UserDaoSql.getInstance().list(OrderPostmanTrouble.class, selectSql.toString());
            count = UserDaoSql.getInstance().getCount(countSql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isAbsList(list)) {
            List<OrderPostmanTroubleVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }

                OrderPostmanTroubleVO vo = new OrderPostmanTroubleVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), vo, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }

                if (ValidateUtil.isNotNull(vo.getUsername())) {
                    UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(vo.getUsername());
                    if (null == userInfo) {
                        continue;
                    }
                    vo.setName(userInfo.getName());
                    vo.setSignPhoto(userInfo.getSignPhoto());
                }

                voList.add(vo);
            }
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(count, voList.size(), voList);
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }

    //获取配送员的最新位置  公司
    @RequestMapping(method = RequestMethod.POST, value = "/company/postman/position/get")
    @ResponseBody
    public String get_postman_position_full(String token, String postmanUsername) {
        //验证用户有效性
//        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
//        if (user == null) {
//            return AjaxResult.errorLogoutResult();
//        }
//        PostCompanyInfo postCompanyInfo = PostCompanyMemory.getInstance().getByUsername(user.getUsername());
//        if (postCompanyInfo == null) {
//            return AjaxResult.errorResult("未获取到公司信息");
//        }

        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(postmanUsername);
        if (null == cityPostman) {
            return AjaxResult.errorResult("当前配送员不存在，请查证");
        }
        PostmanPositionInfo info = PostmanPositionMemory.getInstance().get(cityPostman.getId());
        if (null != info) {
            Integer count = OrderInfoMemory.getInstance().countOfDeliveryIng(postmanUsername);
            if (ValidateUtil.isAbsInteger(count)) {
                info.setOrderCount(count);
            }
        }
        return AjaxResult.successResult(info);
    }
    // 公司转单
    @RequestMapping(method = RequestMethod.POST, value = "/company/order/change")
    @ResponseBody
    public String admin_order_postman(String token, String orderNo, String fromUsername, String toUsername) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        PostCompanyInfo postCompanyInfo = PostCompanyMemory.getInstance().getByUsername(user.getUsername());
        if (postCompanyInfo == null) {
            return AjaxResult.errorResult("未获取到公司信息");
        }
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("请选择订单");
        }
        ResultInfo resultInfo = OrderMan.changePostman(orderNo, fromUsername, toUsername, user.getUsername(), true);
        if (null == resultInfo) {
            return AjaxResult.errorResult("转单失败，请稍后重试。");
        } else if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }
        return AjaxResult.successResult();
    }

}
